(function () {
    var houseId=common.getQueryString("houseId");
    var houseNo=common.getQueryString("houseNo");
//给隐藏域赋值，做条件搜索
    $("#houseId").val(houseId);
//获取dom，用来操作audio点击播放器
    var audio=$("#data-audio");
    var audioName=$("#audio-name");
    //获取二维码容器
    var $QrCode=$("#QR-code");
    //配置二维码连接
    var links=window.houseAudioLink;
    links+="?houseId="+houseId;
    var blobUrl = common.createQRCode($QrCode,links);
    $(".qr-code").html('<img src="'+blobUrl+'" />');
    $("#qr-down").attr("href",blobUrl).attr("download","audio_"+houseNo);
    var updateAudioCoverPhoto = function (path) {
       var sendData= {
           houseId:houseId,
           cover:path
       };
       $.post(window.globalHost+common.uploadAudioCoverPhotoPath,sendData).success(function (data) {
           layer.alert(data.res.msg);
       });
    };
    var $audioCoverPhoto=$("#audio-cover-photo");
    window.getAudioCoverPhoto = function (data) {
        var coverPhotoPath = data.houseInfo.cover.split(",");
        var coverPhotoGallery=$audioCoverPhoto.html("").gallery({
            readOnly:false,
            title:"上传音频封面图片",
            url:window.globalHost +common.uploadImagePort,
            paramName:"uploadData",
            fileFolder:{folder:"house",id:houseId,fileName:"sys_audio_"+new Date().getTime()},
            returnPathName:"filePath",
            maxFiles:1,
            filePaths:coverPhotoPath?coverPhotoPath:[],
            uploadCallback:function () {
                var path=coverPhotoGallery.getFilePaths();
                updateAudioCoverPhoto(path.join(","));
            },
            deleteCallback:function () {
                var path=coverPhotoGallery.getFilePaths();
            }
        });
    };

//声明全局删除容器
    var checkedObject = {};
//配置dataTables项
    var settings = {
        "sAjaxSource": window.globalHost + common.audioListPath,
        "iDisplayLength": 20,
        "bPaginate":false,
        "aoColumns": [{
            "mDataProp": function (obj) {
                return '<span class="dataId" data-id="'+obj.id+'">'+obj.sort+'</span>'
            },
            "sTitle": "序号",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": function (obj) {
                var checkboxItemStr = '<input id="checkbox-' + obj.id + '" type="checkbox" >';
                if (checkedObject[obj.id]) {
                    checkboxItemStr = '<input id="checkbox-' + obj.id + '" type="checkbox" checked="checked">';
                }
                return '<div class="checkbox checkbox-danger" style="width:100%">' + checkboxItemStr + '<label for="checkbox-' + obj.id + '" style="width:80%"></label></div>'
            },
            "sTitle": "批量",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp":"audioName",
            "sTitle": "音频名称",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": function (obj) {
                var path = obj.audioPath;
                return '<a href="javascript:;" class="audio-play" data-name="'+obj.audioName+'" data-source="'+path+'">'+obj.fileName+'</a>'
            },
            "sTitle": "文件名",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": "updateTime",
            "sTitle": "更新时间",
            "sDefaultContent": "",
            "sClass": "center"
        },{
            "mDataProp": function (obj) {
                var status = obj.status;
                var btnStyle = status==='AVAILABLE'?"danger":"info";
                var btnText = status==='AVAILABLE'? '禁用':'启用';
                var changeBtn;
                changeBtn='<a href="javascript:;" class="btn btn-'+btnStyle+' col-xs-5 pull-right status-change" data-status="'+status+'" data-id="'+obj.id+'">'+btnText+'</a>'
                return '<a href="javascript:;" class="btn btn-success col-xs-5 pull-left editor" data-id="'+obj.id+'">编辑</a>'+changeBtn;
            },
            "sTitle": "操作",
            "sDefaultContent": "",
            "sClass": "clearfix"
        }],
        "fnServerParams": function (aoData) {
            // $('select').attr("disabled",true);
            return common.getSearchData("form.data-list-search", aoData);
        }
    };
//渲染列表
    var options = $.extend(true, {}, _dataTableSettings, settings);
    var $currentDataTable = $("#data-list");
    var oTable = $currentDataTable.dataTable(options);
//调用jqueryUI的sortTable用来操作拖动排序
    var tBody=$currentDataTable.find("tbody");
    tBody.disableSelection().sortable({
        update:function (e, u) {
            var self = $(this);
            var dataIds=self.find(".dataId");
            var sortIds = [];
            dataIds.map(function (idx,ele) {
                var $ele=$(ele);
                sortIds.push($ele.attr("data-id"));
            });
            sortIds = sortIds.join(",");
            $.post(window.globalHost+common.audioSortPath,{houseId:houseId,ids:sortIds}).success(function (data) {
                var code = data.code;
                if(code==0){
                    oTable.fnClearTable();
                }else{
                    layer.alert(data.res.msg);
                    self.sortable("cancel");
                }
            }).error(function (x, h, r) {
                layer.alert("网络不畅,请稍后再试");
                self.sortable("cancel");
            })
        }
    });
//实现点击文件名，播放对应音频名称的音乐
    $currentDataTable.off("click",".audio-play").on("click",".audio-play",function (e) {
        var self = $(this);
        var selfPath = self.attr("data-source");
        var selfName = self.attr("data-name");
        audio.attr("src",selfPath);
        audioName.html(selfName);
        audio[0].play();
        e.stopPropagation();
        e.preventDefault();
    });
//更新音频使用状态
    $currentDataTable.off("click",".status-change").on("click",".status-change",function (e) {
        initMedia();
        var self = $(this);
        var status = self.attr("data-status");
        var selfId = self.attr("data-id");
        var sendData = {
            id:selfId,
            status:status==='AVAILABLE'?"FORBID":"AVAILABLE"
        };
        common.updateLock({
            confirmMsg:"确定更新状态吗？",
            path:common.changeAudioStatusPath,
            sendData:sendData,
            listPanel:oTable
        });
        e.stopPropagation();
        e.preventDefault();
    });
//查看和编辑音频信息
    $currentDataTable.off("click",".editor").on("click",".editor",function (e) {
        initMedia();
        var self = $(this);
        var selfId = self.attr("data-id");
        common.openInsertDialog({
            'url': './rewardHouse/audioInfo.html?audioId='+selfId,
            'title': '音频详情',
            'sAjaxSource': window.globalHost + common.updateAudioPath,
            'area': ['1000px', '600px'],
            'btn': '保存',
            ok: function () {
                oTable.fnClearTable();
            }
        });
        e.stopPropagation();
        e.preventDefault();
    });
//添加音乐操作
    $("button.insertAudio").on('click', function (ev) {
        initMedia();
        common.openInsertDialog({
            'url': './rewardHouse/insertAudio.html?houseNo='+houseNo+'&houseId='+houseId,
            'title': '添加音频',
            'sAjaxSource': window.globalHost + common.addAudioPath,
            'area': ['1000px', '600px'],
            'btn': '保存',
            ok: function () {
                oTable.fnClearTable();
            }
        });
        ev.stopPropagation();
    });
//点击复选框操作
    $currentDataTable.on("change", ".checkbox", function(ev) {
        var checkItem = $(this).find("input[type='checkbox']")[0];
        var checkId = checkItem.id.replace('checkbox-', '');
        if (checkItem.checked) {
            checkedObject[checkId] = true;
        } else {
            delete checkedObject[checkId];
        }
        ev.stopPropagation();
    });
//删除音频操作
    $("button.delAudio").on('click', function (ev) {
        initMedia();
        common.deleteConfirm(batchDelete);
        ev.stopPropagation();
    });
    function batchDelete() {
        var ids = [];
        if ($.isEmptyObject(checkedObject)) {
            layer.alert("请选择需要删除的音频 !");
            return;
        }
        $.each(checkedObject, function(i, I) {
            ids.push(i);
        });
        ids = ids.join();
        $.post(window.globalHost + common.delAudioPath, { ids: ids }).success(function(data) {
            var record = common.transformData(data);
            layer.alert(record.res.msg);
            /**
             * 删除成功之后，清除本地的checkbox缓存。
             * @type {Object}
             */
            checkedObject = {};
            /**
             * 批量删除成功之后，刷新列表
             */
            oTable.fnClearTable();
        });
    }
//初始化播放器
    function initMedia() {
        audio[0].pause();
        audio.attr("src","");
        audioName.html("音频名称");
    }
}).call(this)